package com.le.sarrs.util;

import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import ch.qos.logback.core.joran.spi.JoranException;
import ch.qos.logback.core.util.StatusPrinter;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.io.ClassPathResource;

import java.io.IOException;
import java.net.URL;

/**
 * 获取spring管理的bean对象工具类
 * @author yangchao
 * 2016年3月9日 上午10:47:49
 */
public final class SpringUtil implements ApplicationContextAware {
    private static ApplicationContext applicationContext;
    private String log4jConfigure;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext){
        SpringUtil.applicationContext = applicationContext;
        System.out.println("SpringUtil loading logback configure:" + log4jConfigure);
        try {
            load(log4jConfigure);
        } catch (IOException | JoranException| BeansException e) {
            e.printStackTrace();
        }
    }


    public static Object get(String name) {
        return applicationContext.getBean(name);
    }

    public void setLog4jConfigure(String log4jConfigure) {
        this.log4jConfigure = log4jConfigure;
    }

    private static void load(String externalConfigFileLocation) throws IOException, JoranException {
        URL logURL = new ClassPathResource(externalConfigFileLocation).getURL();
        LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
        JoranConfigurator configurator = new JoranConfigurator();
        configurator.setContext(lc);
        lc.reset();
        configurator.doConfigure(logURL);
        StatusPrinter.printInCaseOfErrorsOrWarnings(lc);
    }
}
